import { closeStyleHandle } from './styleGroup.js'
const addIcon = require('@/assets/icons/style/add.png')
const textIcon = require('@/assets/icons/style/text.png')
const highlightIcon = require('@/assets/icons/style/highlight.png')

const controls = document.createElement('div')
controls.id = 'highlight-chunk-controls'
controls.innerHTML = `
  <img class="highlight-icon" src="${addIcon}" title="点击打开菜单"/>
  <div class="controls-float" style="visibility:hidden">
    <p class="highlight"><img src="${require('@/assets/icons/style/highlight.png')}" />高亮块</p>
    <p title="清除格式" class="clear"><img src="${require('@/assets/icons/style/clear.png')}" />清除样式</p>
    <div class="isEmpty">
        <div class="line-nodel"></div>
        <p class="copy"><img src="${require('@/assets/icons/style/copy.png')}" />复制</p>
        <p class="cut"><img src="${require('@/assets/icons/style/cut.png')}" />剪切</p>
        <p class="del"><img src="${require('@/assets/icons/style/del.png')}" />删除</p>
        <div class="line-nodel"></div>
        <p title="前插空行" class="topset"><img src="${require('@/assets/icons/style/topset.png')}" />在上方插入空行</p>
        <p title="后插空行" class="bottomset"><img src="${require('@/assets/icons/style/bottomset.png')}" />在下方插入空行</p>
    </div>
  </div>
  `
// 独立调色板 dom结构
const colorPalette = document.createElement('div')
const clearDom = controls.querySelector('.clear')
colorPalette.id = 'color-palette-controls'
colorPalette.innerHTML = `
<div class="icon-bx">
    <img src="${require('@/assets/icons/editor/palette.png')}" />
    <img class="option-active" src="${require('@/assets/icons/editor/chevron-down@2x(1).png')}" />
</div>
<div class="color-palette-library" style="visibility:hidden">
    <div class="title">
    <span>字体颜色</span>
    <img src="${require('@/assets/icons/style/get-color.png')}" />
    <input type="color" id="text-color" class="select-color" name="head" value="#e66465" />
    </div>
    <div class="fast-wrap text-list">
    ${generateColorList('text')}
    </div>
    <div class="title">
    <span>边框颜色</span>
    <img src="${require('@/assets/icons/style/get-color.png')}" />
    <input type="color" id="border-color" class="select-color " name="head" value="#e66465" />
    </div>
    <div class="fast-wrap border-list">
    ${generateColorList('border')}
    </div>
    <div class="title">
    <span>背景颜色</span>
    <img src="${require('@/assets/icons/style/get-color.png')}" />
    <input type="color" id="bg-color" class="select-color" name="head" value="#e66465" />
    </div>
    <div class="fast-wrap bg-list">
    ${generateColorList('bg')}
    </div>
    <div class="line-nodel"></div>
    <div id="reset-color">恢复默认</div>
</div>
`
let isShowControls = false
let isShowColorPalette = false
const controlsIcon = controls.querySelectorAll('.highlight-icon')[0]
const isEmpty = controls.querySelectorAll('.isEmpty')[0]
// 高亮块dom & 高亮块父级
const controlsDom = controls.querySelectorAll('.controls-float')[0]
// 调色板dom & 调色板父级
const textColor = colorPalette.querySelectorAll('#text-color')[0]
let optionActive = colorPalette.querySelector('.option-active')
const borderColor = colorPalette.querySelectorAll('#border-color')[0]
const bgColor = colorPalette.querySelectorAll('#bg-color')[0]
const resetColor = colorPalette.querySelectorAll('#reset-color')[0]
const colorPaletteDom = colorPalette.querySelectorAll('.color-palette-library')[0]
let oldTop = 0;
let oldscrollTop = 0;
let chunkDom = null;
let iframeDom = null
let tinymceDom = null
// 有效块级元素
let effectiveChunk = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'div', 'ul']
let activeEditor = null
function highlightInit(editor){
    activeEditor = editor
    document.querySelectorAll('.tox-sidebar-wrap')[0].appendChild(controls)
    document.querySelectorAll('.tox-sidebar-wrap')[0].appendChild(colorPalette)
    tinymceDom = editor.dom.select('#tinymce')[0]
    iframeDom = document.querySelectorAll(`#${editor.id}_ifr`)[0]
    tinymceDom.addEventListener('mousemove', mouseMove)
    iframeDom.contentWindow.document.addEventListener('scroll', scrollHandle)
    iframeDom.addEventListener('mouseout', moveOut)
    editor.on('click', clickHandle)

};
// 编辑器点击事件
function clickHandle(e) {
    closeControls()
    mouseMove(e)
}
// 关闭高亮块菜单
function closeControls() {
    controlsDom.style.visibility = 'hidden'
    controlsDom.style.transform = 'scale(.8)'
    controlsDom.style.opacity = '0'
    isShowControls = false
    colorPaletteDom.style.visibility = 'hidden'
    colorPaletteDom.style.transform = 'scale(.8)'
    colorPaletteDom.style.opacity = '0'
    isShowColorPalette = false
}
// 鼠标移动事件
function mouseMove(e) {
    // 过滤样式库中点击事件
    let hasClassName = ['divide-box', 'css-box-item','insert-element']
    let findinsertDom = null
    let childInsertDom = null
    if (e.target != chunkDom){
        findinsertDom = findParentWithClass(e.target, hasClassName)
        if (e.target.getAttribute('id') != 'tinymce'){
            childInsertDom = hasClassInTwoLevels(e.target, 'divide-box')
        }
    }
    if (findinsertDom || childInsertDom) {
        controls.style.visibility = 'hidden'
        closeControls()
        return false
    }
    // console.log(e,'事件委托')
    if (!isShowControls && !isShowColorPalette) {
        const target = e.target
        let effectiveDom = null
        effectiveDom = findParentWithName(target, effectiveChunk)
        if (effectiveDom) {
            // 获取iframe的滚动条高度
            let scrollTop = iframeDom.contentWindow.document.documentElement.scrollTop
            // 距离父级顶部高度
            let offsetTop = effectiveDom.offsetTop
            let top = offsetTop - scrollTop
            oldTop = top
            oldscrollTop = scrollTop
            controls.style.top = top + 'px'
            controls.style.visibility = 'visible'
            chunkDom = effectiveDom
            const domText = effectiveDom.innerText
            if (domText.trim()) {
                controlsIcon.src = textIcon
                isEmpty.style.display = 'block'
            }else{
                controlsIcon.src = addIcon
                isEmpty.style.display = 'none'
                if (effectiveDom.classList.contains('chunk')){
                    clearDom.style.display = 'block'
                    clearDom.style.marginTop = '2px'
                }else{
                    clearDom.style.display = 'none'
                }

            }
            // 调色板位置
            colorPalette.style.top = (top - 34) + 'px'
            if (e.target.classList.contains('chunk')) {
                colorPalette.style.visibility = 'visible'
                controlsIcon.src = highlightIcon
            }else{
                colorPalette.style.visibility = 'hidden'
            }
        }
    }
}
// 编辑器滚动事件
function scrollHandle(e){
    // 获取iframe的滚动条高度
    let scrollTop = iframeDom.contentWindow.document.documentElement.scrollTop
    if (isShowControls) {
        controls.style.top = (oldTop + oldscrollTop - scrollTop) + 'px'
    }else{
        controls.style.visibility = 'hidden'
    }
    if (isShowColorPalette) {
        colorPalette.style.top = (oldTop + oldscrollTop - scrollTop) - 34 + 'px'
    }else{
        colorPalette.style.visibility = 'hidden'
    }
    closeStyleHandle()
}
// 移出编辑区 自动隐藏
function moveOut(){
    if (!isShowControls) {
        controls.style.visibility = 'hidden'
    }
    if (!isShowColorPalette) {
        colorPalette.style.visibility = 'hidden'
    }
    // chunkDom && activeEditor.dom.removeClass(chunkDom, 'highlight-box-bg highlight-base-box-bg')
    // 更新编辑器的内容
    observer(activeEditor)
}

// 保持左侧小图显示
controls.addEventListener('mouseenter', () => {
    controls.style.visibility = 'visible'
    activeEditor.dom.addClass(chunkDom, 'highlight-base-box-bg')
})
// 保持调色板小图显示
colorPalette.addEventListener('mouseenter', () => {
    colorPalette.style.visibility = 'visible'
})
// 调色板图标点击事件
colorPalette.addEventListener('click', (e) => {
    if (colorPaletteDom.style.visibility == 'hidden') {
        optionActive.style.transform = 'rotate(180deg)'
        colorPaletteDom.style.visibility = 'visible'
        colorPaletteDom.style.transform = 'scale(1)'
        colorPaletteDom.style.opacity = '1'
        isShowColorPalette = true
        let iconRect = e.target.getBoundingClientRect()
        let differenceTop = (window.innerHeight - iconRect.top) - 371
        if (differenceTop < 0) {
            colorPaletteDom.style.top = differenceTop -20 + 'px'
            colorPaletteDom.style.left = '100%'
        }else{
            colorPaletteDom.style.top = ''
            colorPaletteDom.style.left = ''
        }
        // 获取高亮块的颜色用于调色板选中回显
        const color = rgbToHex(chunkDom.style.backgroundColor || 'rgb(254, 248, 232)')
        const parentNode = colorPaletteDom.querySelector('.bg-list')
        for (let i = 0; i < parentNode.children.length; i++) {
            const childNode = parentNode.children[i];
            // 检查子节点是否是元素节点（不是文本节点或注释节点）
            if (childNode.getAttribute('data-color') == color) {
                // 修改子节点的class
                childNode.className = 'active-bg-color'; // 替换你的class名
            } else {
                childNode.className = 'hidden-bg-color'; // 替换你的class名
            }
        }
    } else {
        optionActive.style.transform = 'rotate(0deg)'
        colorPaletteDom.style.visibility = 'hidden'
        colorPaletteDom.style.transform = 'scale(.8)'
        colorPaletteDom.style.opacity = '0'
        isShowColorPalette = false
    }
})
// 背景色rgb转hex
function rgbToHex(rgbString) {
    const rgb = rgbString.match(/\d+/g).map(Number);
    return "#" + ((1 << 24) + (rgb[0] << 16) + (rgb[1] << 8) + rgb[2]).toString(16).slice(1);
}
// 调色板颜色点击事件
colorPaletteDom.addEventListener('click', (e) => {
    let effectiveDom = null
    let effectiveChunk = ['text-list', 'border-list', 'bg-list']
    // 向上找块级元素，最高三层
    if (e.target && effectiveChunk.includes(e.target.classList.item(1))) {
        effectiveDom = e.target.classList.item(1)
    } else if (e.target && effectiveChunk.includes(e.target.parentNode.classList.item(1))) {
        effectiveDom = e.target.parentNode.classList.item(1)
    } else if (e.target && effectiveChunk.includes(e.target.parentNode.parentNode.classList.item(1))) {
        effectiveDom = e.target.parentNode.parentNode.classList.item(1)
    }
    if (e.target.localName == 'span' && effectiveDom === 'bg-list') {
        const parentNode = e.target.parentNode
        for (let i = 0; i < parentNode.childNodes.length; i++) {
            const childNode = parentNode.childNodes[i];
            // 检查子节点是否是元素节点（不是文本节点或注释节点）
            if (childNode.nodeType === 1) {
                // 修改子节点的class
                childNode.className = 'hidden-bg-color'; // 替换你的class名
            }
        }
        const color = e.target.dataset.color || e.target.parentNode.dataset.color
        e.target.classList.remove('hidden-bg-color')
        e.target.classList.add('active-bg-color')
        let styleAttri = chunkDom.getAttribute('data-mce-style') || ''
        styleAttri = replaceOrAppendCssValue(styleAttri, 'background-color', color)
        activeEditor.dom.setAttribs(chunkDom, {
            'data-mce-style': styleAttri,
            'style': styleAttri
        })
    } else if ((e.target.localName == 'span' || e.target.localName == 'img') && effectiveDom === 'border-list') {
        const color = e.target.dataset.color || e.target.parentNode.dataset.color
        let styleAttri = chunkDom.getAttribute('data-mce-style') || ''
        styleAttri = replaceOrAppendCssValue(styleAttri, 'border-color', color)
        activeEditor.dom.setAttribs(chunkDom, {
            'data-mce-style': styleAttri,
            'style': styleAttri
        })
    } else if (e.target.localName == 'span' && effectiveDom === 'text-list') {
        const color = e.target.dataset.color || e.target.parentNode.dataset.color
        let styleAttri = chunkDom.getAttribute('data-mce-style') || ''
        styleAttri = replaceOrAppendCssValue(styleAttri, 'color', color)
        activeEditor.dom.setAttribs(chunkDom, {
            'data-mce-style': styleAttri,
            'style': styleAttri
        })
    }
    e.stopPropagation()
})

// 调色板背景seclet 事件
bgColor.addEventListener('input', (e) => {
    const color = e.target.value
    let styleAttri = chunkDom.getAttribute('data-mce-style') || ''
    styleAttri = replaceOrAppendCssValue(styleAttri, 'background-color', color)
    activeEditor.dom.setAttribs(chunkDom, {
        'data-mce-style': styleAttri,
        'style': styleAttri
    })
})
// 调色板字体seclet 事件
textColor.addEventListener('input', (e) => {
    const color = e.target.value
    let styleAttri = chunkDom.getAttribute('data-mce-style') || ''
    styleAttri = replaceOrAppendCssValue(styleAttri, 'color', color)
    activeEditor.dom.setAttribs(chunkDom, {
        'data-mce-style': styleAttri,
        'style': styleAttri
    })
})
// 调色板边框seclet 事件
borderColor.addEventListener('input', (e) => {
    const color = e.target.value
    let styleAttri = chunkDom.getAttribute('data-mce-style') || ''
    styleAttri = replaceOrAppendCssValue(styleAttri, 'border-color', color)
    activeEditor.dom.setAttribs(chunkDom, {
        'data-mce-style': styleAttri,
        'style': styleAttri
    })
})
// 重置高亮块样式
resetColor.addEventListener('click', () => {
    let style = activeEditor.dom.getAttrib(chunkDom, 'style')
    style = clearColor(style)
    activeEditor.dom.setAttribs(chunkDom, {
        'data-mce-style': style,
        'style': style
    })
})

// 添加左侧按钮点击事件
controlsIcon.addEventListener('click', (e) => {
    // 判断高亮块是否已经设置，如果设置了，隐藏高亮块选项展示清除样式选项。如果没设置，则展示高亮块选项
    if (chunkDom && chunkDom.classList.contains('chunk')) {
        clearDom.style.display = 'block'
        clearDom.style.marginTop = '2px'
    } else {
        clearDom.style.display = 'none'
    }
    closeStyleHandle()

    if (controlsDom.style.visibility == 'hidden') {
        controlsDom.style.visibility = 'visible'
        controlsDom.style.transform = 'scale(1)'
        controlsDom.style.opacity = '1'
        isShowControls = true
        let iconRect = e.target.getBoundingClientRect()
        let differenceTop = (window.innerHeight - iconRect.top) - controlsDom.clientHeight
        if (differenceTop < 0) {
            controlsDom.style.top = differenceTop - 20 + 'px'
            controlsDom.style.right = '120%'
        } else {
            controlsDom.style.top = ''
            controlsDom.style.right = ''
        }
    } else {
        controlsDom.style.visibility = 'hidden'
        controlsDom.style.transform = 'scale(.8)'
        controlsDom.style.opacity = '0'
        isShowControls = false
    }
})
// 面板鼠标移入事件
controlsIcon.addEventListener('mouseover', () => {
    console.log('mouseover', chunkDom)
    chunkDom && chunkDom.classList.add('highlight-box-bg')
})
// 面板鼠标移出事件
controlsIcon.addEventListener('mouseout', () => {
    console.log('mouseout', chunkDom)
    // chunkDom && activeEditor.dom.removeClass(chunkDom, 'highlight-box-bg highlight-base-box-bg')
    closeHighlightActive()
})

// 面板点击事件
controlsDom.addEventListener('click', async (e) => {
    e.stopPropagation()
    const childItem = ['highlight', 'clear', 'copy', 'cut', 'del', 'topset', 'bottomset']
    if (childItem.includes((e.target.className || e.target.parentNode.className))) {
        // 事件类型
        const funType = e.target.className || e.target.parentNode.className
        console.log(funType, '点击事件')
        if (funType == 'highlight') {
            // 添加高亮块
            if (chunkDom) {
                if (chunkDom.classList.contains('chunk')) {
                    // 嵌套高亮块
                    const tempDiv = document.createElement('div');
                    let text = '<div>&nbsp;</div>'
                    console.log(chunkDom.children,'chunkDom.children')
                    if (chunkDom.children.length > 0) {
                        text = Array.from(chunkDom.children).map(node => {
                            return node.outerHTML
                        }).join('')
                    }
                    tempDiv.innerHTML = `<div class="chunk"  data-wrap="outer-sphere">${text ||'&nbsp;'}</div>`, 'text/html';
                    const node = tempDiv.firstChild
                    activeEditor.dom.setHTML(chunkDom,node.outerHTML)
                } else {
                    activeEditor.dom.addClass(chunkDom, 'chunk')
                    // 添加一个空段落
                    const text = chunkDom.textContent
                    activeEditor.dom.setHTML(chunkDom, `<div>${text || '&nbsp;'}</div>`)
                }
            }
        } else if (funType == 'clear') {
            // 清除高亮块
            if (chunkDom) {
                activeEditor.dom.removeClass(chunkDom, 'chunk')
                let styleAttri = chunkDom.getAttribute('data-mce-style') || ''
                styleAttri = clearColor(styleAttri)
                activeEditor.dom.setAttribs(chunkDom, {
                    'data-mce-style': styleAttri,
                    'style': styleAttri
                })
            }
        } else if (funType == 'copy') {
            // 复制高亮块
            if (chunkDom) {
                const rng = activeEditor.dom.createRng();
                rng.setStartBefore(chunkDom); // 设置选区的起始位置在目标元素之前
                rng.setEndAfter(chunkDom);   // 设置选区的结束位置在目标元素之后
                // 使用编辑器的selection对象设置新的选区
                activeEditor.selection.setRng(rng);
                const contentToCopy = activeEditor.selection.getContent({ format: 'html' })// 获取块级元素的HTML内容
                const blob = new Blob([contentToCopy], { type: 'text/html' });
                const item = new ClipboardItem({ 'text/html': blob });
                await navigator.clipboard.write([item]);
                console.log('复制内容成功')
            }

        } else if (funType == 'cut') {
            // 剪切高亮块
            if (chunkDom) {
                const rng = activeEditor.dom.createRng();
                rng.setStartBefore(chunkDom); // 设置选区的起始位置在目标元素之前
                rng.setEndAfter(chunkDom);   // 设置选区的结束位置在目标元素之后
                // 使用编辑器的selection对象设置新的选区
                activeEditor.selection.setRng(rng);
                const contentToCopy = activeEditor.selection.getContent({ format: 'html' })// 获取块级元素的HTML内容
                const blob = new Blob([contentToCopy], { type: 'text/html' });
                const item = new ClipboardItem({ 'text/html': blob });
                await navigator.clipboard.write([item]);
                activeEditor.dom.remove(chunkDom)
            }

        } else if (funType == 'del') {
            // 删除高亮块
            if (chunkDom) {
                activeEditor.dom.remove(chunkDom)
            }

        } else if (funType == 'topset') {
            // 顶部插入一行
            if (chunkDom) {
                const newRow = activeEditor.dom.create('div', {}, '<br>');
                chunkDom.parentNode.insertBefore(newRow, chunkDom)
                observer(activeEditor)
            }
        } else if (funType == 'bottomset') {
            // 底部插入一行
            if (chunkDom) {
                const newRow = activeEditor.dom.create('div', {}, '<br>');
                activeEditor.dom.insertAfter(newRow, chunkDom)
            }
        }
        // 隐藏面板
        controlsDom.style.visibility = 'hidden'
        controlsDom.style.transform = 'scale(.8)'
        controlsDom.style.opacity = '0'
        isShowControls = false
        isShowColorPalette = false
        closeHighlightActive()
    }
})

function replaceOrAppendCssValue(cssString, property, newValue) {
    // 构建正则表达式以匹配特定的CSS属性及后面的值
    let regex = new RegExp(`\\b${property}\\b\\s*:\\s*[^;]+\\s*;`, 'i');
    if (property === 'color') {
        regex = new RegExp(/(?<!\w-)color\s*:\s*([^\s;]+)/)
        console.log('匹配为color')
    }
    // 检查是否找到了匹配项
    if (cssString.match(regex)) {
        // 如果找到匹配项，则替换匹配到的属性值
        let newCssString = cssString.replace(regex, `${property}: ${newValue};`);
        if (property === 'color') {
            newCssString = cssString.replace(regex, `color: ${newValue}`);
        }
        console.log('匹配到已有内容', cssString, '---', newCssString)
        return newCssString
    } else {
        // 如果没有找到匹配项，则将新的属性值添加到字符串末尾
        // 如果cssString中没有结尾的分号，需要额外的逻辑来处理。
        console.log('没有匹配到已有内容,准备添加', cssString)
        return cssString.trim().endsWith(';') || !cssString
            ? `${cssString} ${property}: ${newValue};`
            : `${cssString}; ${property}: ${newValue};`;
    }
}

// 关闭高亮块聚焦
function closeHighlightActive(){
    chunkDom && chunkDom.classList.remove('highlight-box-bg', 'highlight-base-box-bg')
}
function clearColor(cssText) {
    const regex = /(?:color|border-color|background-color)\s*:\s*[^;]+;/g;
    const cleanedCssText = cssText.replace(regex, '')
    return cleanedCssText
}

function generateColorList(type) {
    //  生成颜色结构列表
    const colorPaletteTextList = [
        // 基础颜色
        { hex: "#000000", text: 'A' },
        { hex: "#FFFFFF", text: 'A' },
        { hex: "#d8dbe3", text: 'A' },
        { hex: "#b9becc", text: 'A' },
        { hex: "#78839c", text: 'A' },
        { hex: "#3e4d71", text: 'A' },
        { hex: "#5f483c", text: 'A' },
        { hex: "#438268", text: 'A' },
        { hex: "#5584fb", text: 'A' },

        // 深色系列
        { hex: "#63449e", text: 'A' },
        { hex: "#9d2c70", text: 'A' },
        { hex: "#cb4b45", text: 'A' },
        { hex: "#e1bc5d", text: 'A' },
        { hex: "#f49f55", text: 'A' },
        { hex: "#f18130", text: 'A' },

        // 亮色系列
        { hex: "#ea72f3", text: 'A' },
        { hex: "#4273ed", text: 'A' },
        { hex: "#7280ff", text: 'A' },
        { hex: "#2781b3", text: 'A' },
        { hex: "#0599ec", text: 'A' },
    ];
    const colorPaletteBorderList = [
        // 基础颜色
        { hex: "transparent", text: '/' },
        { hex: "#e5e5e5", text: '/' },
        { hex: "#c0cee7", text: '/' },
        { hex: "#f1ba66", text: '/' },
        { hex: "#6f94f1", text: '/' },
        { hex: "#ab77e8", text: '/' },
        { hex: "#ea72f3", text: '/' },
        { hex: "#7ab757", text: '/' },
        { hex: "#5584fb", text: '/' },
        { hex: "#5374c6", text: '/' }
    ];
    const colorPaletteBgList = [
        // 基础颜色
        { hex: "#FFFFFF", text: '&check;' },
        { hex: "#f5f5f5", text: '&check;' },
        { hex: "#faf3f3", text: '&check;' },
        { hex: "#fcf0e1", text: '&check;' },
        { hex: "#f8f5eb", text: '&check;' },
        { hex: "#eaf4e5", text: '&check;' },
        { hex: "#f0ebf6", text: '&check;' },
        { hex: "#eaedfa", text: '&check;' },
        { hex: "#eaedfa", text: '&check;' },
        { hex: "#eaedfa", text: '&check;' },

        // 深色系列
        { hex: "#d8d9d9", text: '&check;' },
        { hex: "#f0f0f0", text: '&check;' },
        { hex: "#f8eded", text: '&check;' },
        { hex: "#fbe8d2", text: '&check;' },
        { hex: "#fefad5", text: '&check;' },
        { hex: "#eaf2f0", text: '&check;' },
        { hex: "#dfd7f2", text: '&check;' },
        { hex: "#d5d9ff", text: '&check;' },
        { hex: "#ccdafe", text: '&check;' },
        { hex: "#cbd5ee", text: '&check;' },

        // 亮色系列
        { hex: "#b5b6b8", text: '&check;' },
        { hex: "#ebebeb", text: '&check;' },
        { hex: "#f1dbdb", text: '&check;' },
        { hex: "#f6d1a4", text: '&check;' },
        { hex: "#fdf5aa", text: '&check;' },
        { hex: "#d4e5e0", text: '&check;' },
        { hex: "#bfb0e4", text: '&check;' },
        { hex: "#aab3ff", text: '&check;' },
        { hex: "#99b5fd", text: '&check;' },
        { hex: "#98acdd", text: '&check;' },
        // 亮色系列
        { hex: "#646568", text: '&check;' },
        { hex: "#e6e6e6", text: '&check;' },
        { hex: "#e7c3c3", text: '&check;' },
        { hex: "#f0b268", text: '&check;' },
        { hex: "#fbee72", text: '&check;' },
        { hex: "#b8d3cc", text: '&check;' },
        { hex: "#957bd2", text: '&check;' },
        { hex: "#7280ff", text: '&check;' },
        { hex: "#5584fb", text: '&check;' },
        { hex: "#5374c6", text: '&check;' },
    ];
    let tempList = []
    if (type == 'text') {
        tempList = colorPaletteTextList
    } else if (type == 'bg') {
        tempList = colorPaletteBgList
    } else if (type == 'border') {
        tempList = colorPaletteBorderList
    }
    // 快捷取色块颜色列表
    if (tempList.length > 0) {
        tempList = tempList.map(item => {
            let childDom = '';
            if (type == 'text') {
                let style = `width: 18px;height: 18px;display: block;margin: 0;padding: 0;border: none;line-height: 18px;font-weight: 500;color:${item.hex}`
                childDom = `<span data-color="${item.hex}" style="border-color:#dfe0e1;background:${item.hex === '#FFFFFF' ? '#dfe0e1' : '#FFFFFF'}">
            <span style="${style}">${item.text}</span>
            </span>`
            } else if (type == 'bg') {
                let style = `width: 18px;height: 18px;margin: 0;padding: 0;border: none;line-height: 18px;font-weight: 500;color:#fff;`
                childDom = `<span data-color="${item.hex}" class="hidden-bg-color" style="background:${item.hex};border-color:${item.hex === '#FFFFFF' ? '#dfe0e1' : 'transparent'}"">
            <span style="${style}">${item.text}</span>
            </span>`
            } else if (type == 'border') {
                let style = `width: 20px;height: 20px;display: ${item.hex === 'transparent' ? 'block' : 'none'};margin: 0;padding: 0;border: none;line-height: 18px;font-weight: 500;color:${item.hex};z-index: 9;`
                childDom = `<span data-color="${item.hex}" style="background:transparent;border-color:${item.hex}">
            <img style="${style}" data-color="${item.hex}" src="${require('@/assets/icons/style/border-icon.png')}" />
            </span>`
            }
            return childDom
        })
    }
    return tempList.join('')
}

// 找到指定dom
function findParentWithClass(element, className) {
    if (!element || element === tinymceDom) {
        return false;
    }
    if (className instanceof Array) {
        let flag = className.some(item => element.classList?.contains(item))
        if (flag) {
            return element
        }
    } else {
        if (element.classList.contains(className)) {
            return element;
        }
    }
    return findParentWithClass(element.parentNode, className);
}

function findParentWithName(element, nodeName) {
    if (!element || element === tinymceDom) {
        return false;
    }
    if (nodeName instanceof Array) {
        let flag = nodeName.some(item => element.localName == item)
        if (flag) {
            return element
        }
    } else {
        if (element.localName == nodeName) {
            return element;
        }
    }
    return findParentWithName(element.parentNode, nodeName);
}

function hasClassInTwoLevels(element, className) {
    // 检查当前元素是否包含指定的类名
    if (element.classList.contains(className)) {
        return true;
    }

    // 获取当前元素的一级子元素
    var children = element.children;
    for (var i = 0; i < children.length; i++) {
        // 检查一级子元素是否包含指定的类名
        if (hasClassInTwoLevels(children[i], className)) {
            return true;
        }
    }

    return false; // 没有找到包含指定类名的元素
}

function observer(editor){
    setTimeout(()=>{
        editor.execCommand('mceRepaint');
    },0)
};

export {
    highlightInit,
    observer,
    closeControls,
    closeHighlightActive
}
